package com.foreknow.demo13;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 功能类
 */
public class Manager {
    /**
     * 写方法
     * 选取流
     * 方法要有一个参数List<Student> student
     */
    public void writeFile(List<Student> list,String fileName) {
        //使用BufferedWriter和FileWriter
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(fileName);
            bw = new BufferedWriter(fw);
            //遍历list集合，每遍历一次获取到一个学生对象
            Iterator<Student> it = list.iterator();
            while (it.hasNext()) {
                Student student = it.next();
                String str = student.getId()+ " "+student.getName()+" "+student.getAge()+" "+student.getPhone()+" "+student.getSchool();
                bw.write(str);
                bw.flush(); //刷新
                bw.newLine();
            }
            bw.close();
            fw.close();
            //获取到学生的信息并将这些信息写到student.txt文件中（注意：空格）
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 读文件
     * @param fileName 文件名
     * @return List<Student>
     */
    public List<Student> readFile(String fileName) {
        FileReader fr = null; //节点流
        BufferedReader br = null;
        List<Student> list = new ArrayList<>();
        try {
            fr = new FileReader(fileName);
            br = new BufferedReader(fr); //处理流(对节点流功能的增强)
            String temp;
            while ((temp = br.readLine())!= null) { //1001 tom 12 12121212 neu
                //拆分字符串
                String[] str = temp.split(" ");
                //将拆分之后的数据以Student对象保存到list集合中
                Student student = new Student();
                student.setId(Integer.parseInt(str[0]));
                student.setName(str[1]);
                student.setAge(Integer.parseInt(str[2]));
                student.setPhone(str[3]);
                student.setSchool(str[4]);
                list.add(student);
            }
            br.close();
            fr.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
